import { _decorator, Component, Node, Vec2, Vec3, randomRange, math } from 'cc';
import { EventManager, MyEvent } from './EventManager';
import { FallItemManager } from './FallItemManager';
const { ccclass, property } = _decorator;

@ccclass('BallMotion')
export class BallMotion extends Component {

    @property(Node)
    circleCenter: Node = null!;       // 圆心对象

    @property
    circleRadius: number = 5;         // 圆半径

    @property
    cowRadius: number = 0.5;

    @property(Vec2)
    velocity: Vec2 = new Vec2(2, 1);  // 初始速度

    @property
    maxAngleOffset: number = 15;      // 碰撞时随机偏移角度（度）

    @property
    speed: number = 100;              // 初始速度系数

    @property
    addSpeed: number = 1;             // 每次碰撞增加的速度

    @property
    gravity: number = 10;

    @property
    timer: number = 5;

    @property
    minSpeed: number = 5;

    @property
    maxSpeed: number = 5;

    private _curTimer: number = 0;
    private _isPause: boolean = false;

    protected start(): void {
    }

    update(dt: number) {
        if (!FallItemManager.Instance.IsStart) return;
        if (this._isPause) return;
        // === 移动小球 ===

        this.velocity.y += dt * this.gravity;
        if (Math.abs(this.velocity.y) < 1) {
            this._curTimer += dt;
        } else {
            this._curTimer = 0;
        }

        const delta = new Vec2(this.velocity.x, this.velocity.y).multiplyScalar(dt * this.speed);

        let cowPos2D = new Vec2(this.node.getWorldPosition().x, this.node.getWorldPosition().y).add(delta);

        // === 检查边界 ===
        const center2D = new Vec2(this.circleCenter.getWorldPosition().x, this.circleCenter.getWorldPosition().y);
        const dist = cowPos2D.clone().subtract(center2D).length();

        if (dist + this.cowRadius >= this.circleRadius) {
            // 计算法线
            const normal = cowPos2D.clone().subtract(center2D).normalize();

            // 反射速度
            const reflectDir = this.reflect(this.velocity.clone(), normal.clone());

            // 加随机角度
            const randomAngle = randomRange(-this.maxAngleOffset, this.maxAngleOffset);
            const rotated = this.rotateVector(reflectDir, randomAngle);

            // 更新速度和加速
            this.velocity = rotated;
            this.speed = math.clamp(this.speed + this.addSpeed, this.minSpeed, this.maxSpeed);
            if (this._curTimer > this.timer) {
                this.velocity.add2f(0, 3);
                this._curTimer = 0;
            }
            // 推回边界
            cowPos2D = center2D.add(normal.multiplyScalar(this.circleRadius - this.cowRadius));
        }

        // === 应用位置 ===
        this.node.setWorldPosition(new Vec3(cowPos2D.x, cowPos2D.y, this.node.getWorldPosition().z));
    }

    /** 向量反射 */
    private reflect(v: Vec2, n: Vec2): Vec2 {
        // v - 2*(v·n)*n
        const dot = v.dot(n);
        return v.subtract(n.multiplyScalar(2 * dot));
    }

    /** 向量旋转 */
    private rotateVector(v: Vec2, angleDeg: number): Vec2 {
        const rad = angleDeg * Math.PI / 180;
        const cos = Math.cos(rad);
        const sin = Math.sin(rad);
        return new Vec2(
            v.x * cos - v.y * sin,
            v.x * sin + v.y * cos
        );
    }

    private pause() {
        this._isPause = !this._isPause;
    }

    protected onEnable(): void {
        EventManager.on(MyEvent.PAUSE, this.pause, this);
    }

    protected onDisable(): void {
        EventManager.off(MyEvent.PAUSE, this.pause, this);
    }
}
